import { ModalForm, ProFormSelect, ProFormText } from '@ant-design/pro-form';
import { Button, Form, Popconfirm, Tag } from 'antd';
import type { FC } from 'react';
import { useModel } from 'umi';

import * as c from '@/services/consts';
import * as apiServiceSet from '@/services/serviceSet';
import * as utils from '@/utils/utils';

type AuthFormProps = {
  visible: boolean;
  current: API.UserModel | undefined;
  onCancel: () => void;
  onSubmit: (values: API.UserAuthModel) => Promise<void>;
};

const AuthForm: FC<AuthFormProps> = (props) => {
  const { visible, current, onCancel, onSubmit } = props;
  if (!visible) {
    return null;
  }

  const { getProductOptions } = useModel('useGlobalModel', (model) => ({
    getProductOptions: model.getProductOptions,
  }));

  const productOptions = getProductOptions(false);

  const loadServiceSets = async (params: { [key: string]: any }) => {
    const selectItems = await apiServiceSet.select(params);

    return Promise.resolve(selectItems);
  };

  const renderExpireTime = (record?: API.UserModel) => {
    if (!record || !record.serviceType) {
      return <></>;
    }
    if (record.serviceType.expireDays < 1) {
      return (
        // <Tag color="error" key={record.serviceType.id}>
        //   {utils.formatUtcToLocal(record.serviceType.expireTime)}
        // </Tag>
        <span style={{ color: '#ff4d4f' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    } else if (
      record.serviceType.expireDays >= 1 &&
      record.serviceType.expireDays <= 7
    ) {
      return (
        <span style={{ color: '#faad14' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    } else {
      return (
        <span style={{ color: '' }}>
          {utils.formatUtcToLocal(record.serviceType.expireTime)}
        </span>
      );
    }
  };

  const renderCurrentAuthExpireTime = (record?: API.UserModel) => {
    if (!record || !record.serviceType) {
      return null;
    }

    const st = record.serviceType;

    return (
      <>
        <Tag
          color={
            st.memberLevel > c.MemberLevel.Free.value ? 'success' : 'default'
          }
        >
          {st.name}
        </Tag>
        {renderExpireTime(record)}
      </>
    );
  };

  return (
    <ModalForm<API.UserAuthModel>
      layout="horizontal"
      labelCol={{ span: 4 }}
      wrapperCol={{ span: 18 }}
      open={visible}
      initialValues={current}
      //preserve={false}
      // trigger={<>{children}</>}
      title={'用户授权'}
      width={640}
      onFinish={onSubmit}
      modalProps={{
        onCancel: onCancel,
        //destroyOnClose: true,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [
            defaultDoms[0],
            <Popconfirm
              key="ok"
              title="确定要给用户授权吗?"
              onConfirm={async () => {
                props.submit();
              }}
            >
              <Button type="primary">确定</Button>
            </Popconfirm>,
          ];
        },
      }}
    >
      <ProFormSelect
        name="productId"
        label="产品"
        options={productOptions}
        readonly={true}
      />
      <ProFormText name="username" label="用户名" readonly />

      <Form.Item label="当前授权">
        {renderCurrentAuthExpireTime(current)}
      </Form.Item>
      <ProFormSelect
        name="serviceSetId"
        label="服务套餐"
        params={{
          productId: current?.productId,
          userId: current?.id,
          channel: c.PurchaseChannel.PMP.value,
        }}
        request={loadServiceSets}
        rules={[{ required: true, message: '请选择服务服务套餐' }]}
      />
    </ModalForm>
  );
};

export default AuthForm;
